from django.shortcuts import render,redirect
from django.views import View
import jsonpickle
from cart.cartmanager import getCartManger
from django.db.transaction import atomic
import json,uuid,datetime
from  utils.alipay import AliPay
from django.db.models import F
from User.models import *
from goods.models import *
from .models import *
from cart.models import *
from django.http import HttpResponse
alipay = AliPay(appid = '2016102300743577',
                return_url = 'http://127.0.0.1:8000/order/checkorder',
                app_notify_url='http://127.0.0.1:8000/order/checkorder',
                app_private_key_path='my_private.txt',
                alipay_public_key_path='alipay_public.txt',
                debug=True)

# Create your views here.
class OrderView(View):
    def get(self,request):
        if not request.session.get('user'):
            return redirect('/user/login?redirect=order&cartitems='+request.GET.get('cartitems'))
        else:

            raw_cartitems = jsonpickle.loads('['+request.GET.get('cartitems')+']')

            request.session['raw_cartitems']= raw_cartitems
            return redirect('/order/order.html')
class OrderListView(View):
    def get(self,request):
        cartitems = request.session.get('raw_cartitems')
        cartManager = getCartManger(request)


        cart_items = [cartManager.get_cartitems(**item) for item in cartitems]
        address = request.session.get('user').address_set.get(isdefault =True)
        totalPrice =0
        for cartItem in cart_items:
            totalPrice+=cartItem.totalPrice()
        return render(request, 'order.html',{'cartitems':cart_items,'address':address,'totalPrice':totalPrice})

class ToOrderView(View):
    @atomic
    def get(self,request):
        cartitems = request.GET.get('cartitems')
        cartitems = json.loads((cartitems))
        print(cartitems)
        raw_order = {
            'address':Address.objects.get(id = request.GET.get('address')),
            'payway':request.GET.get('payway','alipay'),
            'out_trade_num':uuid.uuid4().hex,
            'trade_no':datetime.datetime.today().strftime('%Y%m%d%H%M%S'),
            'user':request.session.get('user')
        }

        order = Order.objects.create(**raw_order)

        total_amount = 0
        for item in cartitems:
            orderItem = OrderItem.objects.create(order=order,**item)
            total_amount+=orderItem.total_price()
            CartItem.objects.filter(user = request.session.get('user'),**item).delete()
            Inventory.objects.filter(goods_id=item['goodsid'],size_id=item['sizeid'],color_id=item['colorid'])\
                .update(count=F('count')-int(item['count']))
        if 'raw_cartitems' in request.session :
            del request.session['raw_cartitems']
        params = alipay.direct_pay(subject='娃哈哈矿泉水',total_amount=total_amount,out_trade_no=order.out_trade_num)
        url = 'https://openapi.alipaydev.com/gateway.do?'+params
        return redirect(url)

class CheckOrderView(View):
    def get(self,request):
        d = request.GET.dict()
        sign = d.pop('sign')
        if alipay.verify(d,sign):
            out_trade_no = d.get('out_trade_no')
            order = Order.objects.get(out_trade_num = out_trade_no)
            if order.status == '待付款':
                order.status = '待发货'
                order.trade_no = d.get('trade_no')
                order.save()
            return HttpResponse('交易成功')
        else:
            return HttpResponse('交易失败')





